package cn.lut.util;

import cn.lut.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @user:dell
 * @date:2020年11月23 13:40
 */
//判断当前请求是否为ajax请求
public class CrowdUtil {
    /*
    对明文字符串进行加密
     */
    public static String md5(String source){
//        1.判断source是否是有效的字符串
        if(source==null||source.length()==0){
//            2.如果不是有效的字符串，抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            //        3.获取messageDigest对象
            String algorithm="md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
//            4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
//            5.执行加密
            byte[] output = messageDigest.digest(input);
//            6.创建bigInteger对象
            int signum=1;
            BigInteger bigInteger = new BigInteger(signum, output);
//            7.按照16进制将bigInteger的值转换为字符串
            int radix=16;
            String encode = bigInteger.toString(radix);
            return encode;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static boolean judgeRequestType(HttpServletRequest request) {
//        1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
//        2.判断
        return (acceptHeader!=null && acceptHeader.contains("application/json"))||(xRequestHeader !=null&&xRequestHeader.equals("XMLHttpRequest"));
    }

}
